package com.atguigu.gmall.common.interceptors;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 远程调用拦截器 用于在微服务之间传递userId
 */
//@Component//为避免影响"依赖service-util但不需要传递userId的微服务"的性能  手动实例化
public class FeignInterceptor implements RequestInterceptor {
    //拦截器 执行方法 远程调用之前执行
    //requestTemplate即马上要发出的请求对象
    //远程调用http协议
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //在SpringIOC容器 任意位置 获取HttpServletRequest
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != servletRequestAttributes) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if (null != request) {
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userId)) {//比如MQ不走http协议 可能传递不了userId 需要判断
                    //放到请求头中, 请求再出发
                    requestTemplate.header("userId", userId);
                }
                if (!StringUtils.isEmpty(userTempId)) {
                    requestTemplate.header("userTempId", userTempId);
                }
            }
        }
    }
}

